﻿using BaseProject.Application.Interfaces;
using BaseProject.Domain.Configs;
using BaseProject.Domain.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Security.Claims;

namespace BaseProject.Application.Implementation
{
    public class FormsAuthenticationImpl : IAuthenticationService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly AppSettingConfig _appSettings;
        private readonly IUserService _userService;
        private User _cachedUser;

        public FormsAuthenticationImpl(IHttpContextAccessor httpContextAccessor, IOptions<AppSettingConfig> settings, IUserService userService)
        {
            this._httpContextAccessor = httpContextAccessor;
            this._appSettings = settings.Value;
            this._userService = userService;
        }

        public async void SignIn(User user)
        {
            _cachedUser = user;

            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name, JsonConvert.SerializeObject(user))
            };
            var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));
            await _httpContextAccessor.HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal);
        }

        public async void SignOut()
        {
            _cachedUser = null;
            await _httpContextAccessor.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }

        public User GetAuthenticatedUser()
        {
            if (!_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                return null;

            var claim = ((ClaimsIdentity)_httpContextAccessor.HttpContext.User.Identity).FindFirst(ClaimTypes.Name);
            return (claim != null) ? JsonConvert.DeserializeObject<User>(claim.Value) : null;
        }
    }
}